<?php

namespace App\Http\Controllers\Mp;

use App\Contract\ContractStatus;
use App\Contract\OrderType;
use App\Http\Controllers\Controller;
use App\Http\Service\AdaPayService;
use App\Http\Service\DeviceService;
use App\Model\Agent;
use App\Model\AgentAmountLog;
use App\Model\Bill;
use App\Model\Business;
use App\Model\BusinessConf;
use App\Model\Contract;
use App\Model\ContractTenant;
use App\Model\Device;
use App\Model\DeviceLog;
use App\Model\Order;
use App\Model\UserRefund;
use App\Service\Baofu;
use App\User;
use App\Utils\Result;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class PaymentController extends Controller
{

    public function rechargeTemp(Request $request)
    {
        $deviceId = $request->input('deviceId');
        $device = Device::query()->with('house', 'rate')->find($deviceId);
        if ($device->recharge_disabled == 1) {
            return Result::error(401, '设备充值受限,请联系管理员');
        }
        if ($device->show_order != 1) {
            return Result::error(401, '设备未开启退费功能，请联系管理员');
        }
        if (!$device->read_at) {
            return Result::error(404, '设备信号不稳定,请3分钟后重新操作');
        }
        $checkOrder = Order::query()->where('device_id', $deviceId)
            ->where('status', 3)
            ->whereIn('recharge_status', [0, 1, 2])
            ->count();
        if ($checkOrder) {
            return Result::error(404, '该电表有在途充值订单，请3分钟后重新扫码充值');
        }
        $targetTime = strtotime($device->read_at);
        $currentTime = time();
        if ($device->is_master == 1) {
            if ($targetTime < ($currentTime - 60)) {
                return Result::error(404, '设备信号不稳定,请3分钟后重新操作');
            }
        } else {
            if ($targetTime < ($currentTime - 720)) {
                return Result::error(404, '设备信号不稳定,请3分钟后重新操作');
            }
        }
        $businessConf = BusinessConf::query()->where('business_id', $device->business_id)->first();
        $user = $this->getUser();
        $checkOrder = Order::where('device_id', $deviceId)
            ->where('type', OrderType::TEMP)
            ->where('status', 5)
            ->with('device', 'business', 'business.user', 'user')
            ->first();
        if ($checkOrder) {
            if ($device->du > 0) {
                return Result::error(404, '改设备已有订单在使用，请联系房东');
            } else {
                $user = User::query()->where('id', $checkOrder->user_id)->first();
                $diff = $checkOrder->device->total - $checkOrder->device_total;
                $use_amount = $checkOrder->device_price * $diff;
                if ($user) {
                    $userName = $user->nickame;
                    if (!$userName) {
                        $userName = $user->mobile;
                    }
                } else {
                    $userName = '临时租客';
                }
                DeviceLog::create([
                    'action' => 9,
                    'device_id' => $checkOrder->device_id,
                    'log' => '租客临时用电' . $diff . '度',
                    'amount' => $use_amount,
                    'user_name' => $userName,
                    'before' => $checkOrder->device_total,
                    'after' => $checkOrder->device->total,
                    'created_at' => $checkOrder->paid_at
                ]);
                if ($checkOrder->device_id) {
                    $deviceModel = $checkOrder->device;
                    if ($deviceModel->agent_id) {
                        $agentModel = Agent::query()->where('id', $deviceModel->agent_id)->first();
                        $allRate = number_format($use_amount * (Agent::MAX_RATE / 100), 2, '.', '');
                        try {
                            if ($agentModel->pid) {
                                $firstAgent = Agent::query()->where('id', $agentModel->pid)->first();
                                $agentType = $firstAgent->type;
                            } else {
                                $firstAgent = $agentModel;
                                $agentType = $agentModel->type;
                            }
                            if ($agentType == 2) {
//                                if (!$deviceModel->business->device_time || time() >= strtotime($deviceModel->business->device_time)) {
//                                    if($deviceModel->business->service > 0 ){
//                                        $agent_service = $deviceModel->business->service;
//                                    }else{
//                                        $agent_service = $firstAgent->service;
//                                    }
//                                    $firstFee = $deviceFee = number_format($agent_service * $diff, 2, '.', '');
//                                    if ($firstAgent->rate > 0) {
//                                        $deviceProfit = $use_amount * ($firstAgent->rate / 100);
//                                    } else {
//                                        $deviceProfit = 0;
//                                    }
//                                    $use_amount -= $deviceFee;
//                                    if ($agentModel->pid && $firstAgent->service > 0) {
//                                        $secondFee = number_format(($firstAgent->service * $agentModel->service / 100) * $diff, 2, '.', '');
//                                        if ($secondFee + $deviceProfit > $deviceFee) {
//                                            $secondFee = $deviceFee - $deviceProfit;
//                                        }
//                                        $firstFee = number_format($deviceFee - $secondFee, 2, '.', '');
//                                        if ($secondFee > 0) {
//                                            $agentModel->amount += $secondFee;
//                                            $agentModel->total_amount += $secondFee;
//                                            $agentModel->total_fee += $use_amount;
//                                            $agentModel->save();
//                                            AgentAmountLog::create([
//                                                'agent_id' => $agentModel->id,
//                                                'type' => $checkOrder->type,
//                                                'amount' => $secondFee,
//                                                'order_id' => $checkOrder->id,
//                                                'device_amount' => $deviceFee,
//                                                'log' => '（临时用电）设备管理费收入',
//                                                'agent_type' => 2,
//                                                'business_id'=>$checkOrder->business_id
//                                            ]);
//                                        }
//                                    }
//                                }
//                                if ($firstFee > 0) {
//                                    $firstFee -= $deviceProfit;
//                                    $firstAgent->amount += $firstFee;
//                                    $firstAgent->total_amount += $firstFee;
//                                    $firstAgent->total_fee += $use_amount;
//                                    $firstAgent->save();
//                                    AgentAmountLog::create([
//                                        'agent_id' => $firstAgent->id,
//                                        'type' => $checkOrder->type,
//                                        'amount' => $firstFee,
//                                        'device_amount' => $deviceFee,
//                                        'order_id' => $checkOrder->id,
//                                        'log' => '（临时用电）设备管理费收入',
//                                        'agent_type' => 2,
//                                        'business_id'=>$checkOrder->business_id
//                                    ]);
//                                }
                            } else {
                                if ($agentModel->rate) {
                                    if ($agentModel->rate > 0.3) {
                                        $agentModel->rate = 0.3;
                                    }
                                    $secAmount = number_format($use_amount * $agentModel->rate / 100, 2, '.', '');
                                    AgentAmountLog::create([
                                        'agent_id' => $agentModel->id,
                                        'type' => $checkOrder->type,
                                        'amount' => $secAmount,
                                        'order_id' => $checkOrder->id,
                                        'log' => '临时用电（线上）分润收入'
                                    ]);

                                    $agentModel->amount += $secAmount;
                                    $agentModel->total_amount += $secAmount;
                                    $agentModel->total_fee += $checkOrder->pay_amt;
                                    $agentModel->save();
                                    $firstAmount = $allRate - $secAmount;
                                    if ($firstAmount > 0 && $agentModel->pid) {
                                        AgentAmountLog::create([
                                            'agent_id' => $firstAgent->id,
                                            'type' => $checkOrder->type,
                                            'amount' => $firstAmount,
                                            'order_id' => $checkOrder->id,
                                            'log' => '临时用电（线上）分润收入'
                                        ]);
                                        $firstAgent->amount += $secAmount;
                                        $firstAgent->total_amount += $secAmount;
                                        $firstAgent->total_fee += $checkOrder->pay_amt;
                                        $firstAgent->save();
                                    }
                                }
                            }
                        } catch (\Exception $e) {

                        }
                    }
                }
                // 写入房东余额
                $fd = $checkOrder->business->user;
                $fd->amount += $use_amount;
                $fd->total_amount += $use_amount;
                $fd->save();
                $checkOrder->status = 4;
                $checkOrder->save();
            }
        }

        $order = new Order();
        $order->user_id = $user->id;
        $order->business_id = $device->business_id;
        $order->type = OrderType::ELECTRIC;
        $order->device_id = $deviceId;
        $order->house_id = $device->house_id;
        $order->order_no = 'D' . date('ymdHis') . rand(1000, 9999);
        $order->pay_channel = $request->input('pay_channel', 'wx_lite');
        $order->pay_amt = $request->input('amount') + $request->input('fee');
        $order->du = $request->input('du') ?? 0;
        $order->goods_title = '临时用电' . $request->input('du');
        $order->goods_desc = '电表设备号：' . $device->sn;
        $order->description = '';
        $order->fee = $request->input('fee') ?? 0;
        $order->service_fee = $request->input('service_fee') ?? 0;
        $order->device_total = $device->total;
        $order->device_price = $device->price;
        $order->type = OrderType::TEMP;
        $agentModel = Agent::query()->where('id', $device->agent_id)->first();
        if ($agentModel->pid) {
            $firstAgent = Agent::query()->where('id', $agentModel->pid)->first();
            $agentType = $firstAgent->type;
        } else {
            $agentType = $agentModel->type;
        }
        if ($agentType == 1) {
            $order->fee = number_format($request->input('amount') * 0.006, 2);
        }
        if ($agentType == 2) {
            $business = Business::query()->where('id', $device->business_id)->first();
            if ($business->device_time && time() < strtotime($business->device_time)) {
                $order->fee = number_format($request->input('amount') * 0.006, 2);
            }
        }
        if ($businessConf && $businessConf->fee_payer == 2) {
            $order->pay_amt = $request->input('amount') + $request->input('fee');
        }

//        $payment = $this->createPaymentOrder($order);
//        if ($payment->isError()) {
//            Log::error('支付出错啦', [$payment->result]);
//            return Result::error(500, '支付出错啦');
//        }
        $baofu = App::make(Baofu::class); // 通过容器解析依赖
        $result = $baofu->createOrder($order, $user);
        $order->save();
        $result['order_no'] = $order->order_no;
//        $result = $payment->result;
        return Result::success($result);

    }

    public function recharge(Request $request)
    {
        $deviceId = $request->input('deviceId');
        $device = Device::query()->with('house', 'rate')->find($deviceId);
        if ($device->recharge_disabled == 1) {
            return Result::error(401, '设备充值受限,请联系管理员');
        }
        if (!$device->read_at) {
            return Result::error(404, '设备信号不稳定,请3分钟后重新操作');
        }
        $checkOrder = Order::query()->where('device_id', $deviceId)
            ->where('status', 3)
            ->whereIn('recharge_status', [0, 1, 2])
            ->count();
        if ($checkOrder) {
            return Result::error(404, '该电表有在途充值订单，请3分钟后重新扫码充值');
        }
        $targetTime = strtotime($device->read_at);
        $currentTime = time();
        if ($device->is_master == 1) {
            if ($targetTime < ($currentTime - 60)) {
                return Result::error(404, '设备信号不稳定,请3分钟后重新操作');
            }
        } else {
            if ($targetTime < ($currentTime - 720)) {
                return Result::error(404, '设备信号不稳定,请3分钟后重新操作');
            }
        }

        try {
            $businessConf = BusinessConf::query()->where('business_id', $device->business_id)->first();
            $businessUserId = Business::query()->where('id', $device->business_id)->value('user_id');
            $businessUser = User::query()->where('id', $businessUserId)->first();
            $all_device = Device::query()->where('business_id', $device->business_id)->get(['id']);
            $currentDate = Carbon::now();
            for ($i = 1; $i <= 3; $i++) {
                // 从当前月份减去 i 个月
                $month = $currentDate->copy()->subMonths($i)->startOfMonth();
                // 格式化月份为 'Y-m' 格式
                $formattedMonth = $month->format('Ym');
                // 将格式化后的月份添加到数组中
                $months[] = $formattedMonth;
            }
            $whiteBool = true;
            $shouldBreak = false;
            foreach ($months as $month) {
                $val = 0;
                foreach ($all_device as $v) {
                    $key = $v->id . '-' . $month;
                    if (Redis::exists($key)) {
                        $val += Redis::get($key);
                    }
                    if ($val >= 100 * 1000) {
                        $shouldBreak = true;
                        break; // 跳出内层循环
                    }
                }
                if ($val < 100 * 1000) {
                    $whiteBool = false;
                }
                if ($shouldBreak) {
                    break; // 跳出外层循环
                }

            }
            if ($whiteBool) {
                if ($businessUser) {
                    $businessUser->white = 1;
                    $businessUser->save();
                }
            }
            if ($businessUser->white != 1) {
                $todayOrderCount = Order::query()->where('type', OrderType::ELECTRIC)
                    //->where('user_id', $this->getUser()->id)
                    ->where('device_id', $deviceId)
                    ->where('status', 3)
                    ->where('created_at', '>', date('Y-m-d 00:00:00'))
                    ->count();
                if ($todayOrderCount > 3) {
                    return Result::error(401, '今日充值已达上限');
                } else {
                    $val = 0;
                    $key = $device->id . '-' . date('Ym');
                    if (Redis::exists($key)) {
                        $val = Redis::get($key);
                    }
                    if ($device->total < 100 && $val < 100 * 1000) {
                        $lastOrder = Order::query()->where('type', OrderType::ELECTRIC)
                            ->where('device_id', $deviceId)
                            ->where('status', 3)
                            ->where('device_price', '>', 0)
                            ->orderBy('id', 'asc')
                            ->limit(2)->get();
                        $allDu = 0;
                        if ($lastOrder->count() === 2) {
                            foreach ($lastOrder as $k => $v) {
                                if ($k == 0) {
                                    $startDu = $v->device_total;
                                }
                                $lastDu = $v->pay_amt / $v->device_price;
                                $lastDu = round($lastDu * 0.2, 1);
                                $allDu += $lastDu;
                            }
                            if ($device->total - $startDu < $allDu) {
                                Log::info('限制原因：' . $device->id . '----device->total:' . $device->total . 'start_du:' . $startDu . 'all_du:' . $allDu);
                                $agent = Agent::query()->where('id', $device->agent_id)->first();
                                if ($agent && $agent->tel_no) {
                                    $tel_no = $agent->tel_no;
                                } else {
                                    $tel_no = '400-926-2566';
                                }
                                return Result::error(402, '请勿频繁电量充值，请联系客服' . $tel_no);
                            }
                        }
                    }
                }
                $monthOrderAmount = Order::query()->where('type', OrderType::ELECTRIC)
                    ->where('device_id', $deviceId)
                    ->where('status', 3)
                    ->where('created_at', '>', now()->firstOfMonth()->toDateString() . ' 00:00:00')
                    ->sum('pay_amt');
                if ($device->total < 500 && $val < 100 * 1000) {
                    if ($monthOrderAmount + $request->input('amount') > $device->month_limit) {
                        return Result::error(401, '本月充值金额超限，提额请联系客服400-926-2566');
                    }
                }
            }

            if ($businessUser && $businessUser->is_disabled == 1) {
                return Result::error(404, '房东账户异常受限');
            }
            // 账号逾期充值限制
            if ($businessConf && $businessConf->is_limit_recharge_days > 0 && !$device->client_id) {
                $failBillCount = Bill::query()->where('house_id', $device->house_id)->where('is_paid', 0)
                    ->where('is_close', 0)
                    ->where('pay_date', Carbon::now()->subDays($businessConf->is_limit_recharge_days)->toDateString())
                    ->count();
                if ($failBillCount > 0) {
                    return Result::error(401, '账单逾期，限制充值');
                }
            }

            $user = $this->getUser();
            $order = new Order();
            $order->user_id = $user->id;
            $order->business_id = $device->business_id;
            $order->type = OrderType::ELECTRIC;
            $order->device_id = $deviceId;
            $order->house_id = $device->house_id;
            $order->order_no = 'D' . date('ymdHis') . rand(1000, 9999);
            $order->pay_channel = $request->input('pay_channel', 'wx_lite');
            $order->pay_amt = $request->input('amount') + $request->input('fee');
            $order->du = $request->input('du') ?? 0;
            if ($device->type == 2) {
                $order->goods_title = '水费充值' . '设备号：' . $device->sn;
                $deviceStr = '水表';
            } else {
                $deviceStr = '电表';
                $order->goods_title = '电费充值' . '设备号：' . $device->sn;
            }
            $order->goods_desc = $deviceStr . '设备号：' . $device->sn;
            $order->description = '';
            $order->fee = $request->input('fee') ?? 0;
            $order->service_fee = $request->input('service_fee') ?? 0;
            $order->device_total = $device->total;
            $order->device_price = $device->price;
            $order->device_du = $device->du;
            $agentModel = Agent::query()->where('id', $device->agent_id)->first();
            if ($agentModel->pid) {
                $firstAgent = Agent::query()->where('id', $agentModel->pid)->first();
                $agentType = $firstAgent->type;
            } else {
                $agentType = $agentModel->type;
            }
            if ($agentType == 1) {
                $order->fee = number_format($request->input('amount') * 0.006, 2);
            }
            if ($request->input('amount')) {
                Log::info('设备单价：' . $device->price.'充值金额：' . $request->input('amount'));
                $order->du = floor($request->input('amount') / $device->price * 100) / 100;
                if ($order->du <= 0) {
                    return Result::error(404, '充电电量不可为0');
                }
            } else {
                return Result::error(404, '充值金额不可为0');
            }
            if ($agentType == 2) {
                $business = Business::query()->where('id', $device->business_id)->first();
                if ($business->device_time) {
                    if(time() > strtotime($business->device_time)){
                        $order->du = floor($request->input('amount') / ($device->price + $business->service) * 100) / 100;
                    }else{
                        $order->fee = number_format($request->input('amount') * 0.006, 2);
                    }
                }else{
                    $order->du = floor($request->input('amount') / ($device->price + $agentModel->service) * 100) / 100;
                }
            }
            if ($businessConf && $businessConf->fee_payer == 2) {
                $order->pay_amt = $request->input('amount') + $order->fee;
            }

//            $payment = $this->createPaymentOrder($order);
//            if ($payment->isError()) {
//                Log::error('支付出错啦', [$payment->result]);
//                return Result::error(500, '支付出错啦');
//            }
            $order->save();
            if ($order->pay_channel != 'wx_lite') {
                $order->pageUrl = $request->input('pageUrl');
            }
            Log::info('第三方订单创建开始' . date('Y-m-d H:i:s'));
            $baofu = App::make(Baofu::class); // 通过容器解析依赖
            $result = $baofu->createOrder($order, $user);
            Log::info('第三方订单创建结束' . date('Y-m-d H:i:s'));
            $result['order_no'] = $order->order_no;
            return Result::success($result);
        } catch (\Exception $e) {
            Log::error('支付出错啦' . $e->getMessage());
            return Result::error(404, $e->getMessage());
        }
    }

    public function billPay(Request $request)
    {
        return Result::error(404, '抱歉！房租线上支付功能暂未开通，请直接联系房东！');
        $billId = $request->input('billId');
        $billList = Bill::query()->with('house', 'house.dianbiao')->whereIn('id', $billId)
            ->where('is_close', 0)
            ->where('is_paid', 0)
            ->get();
        $bill = $billList->first();

        if (!$billList) {
            return Result::error(404, '账单不存在');
        }

        // 是否绑定过电表
//        if ($bill->house && !$bill->house->dianbiao) {
//            return Result::error(401, '房源未绑定电表设备，无法线上支付账单');
//        }

        // 合并支付
        if (count($billList) > 1) {
            $amount = 0;
            $title = '账单合并支付：';
            $goodsDesc = $bill->house->estate_name . $bill->house->name;
            foreach ($billList as $b) {
                $amount += $b->amount;
                $title .= $b->title . ';';
            }
        } else {
            $amount = $bill->amount;
            $title = $bill->title;
            $goodsDesc = $bill->house->estate_name . $bill->house->name . '-' . $bill->title;
        }

        $user = $this->getUser();
        $order = new Order();
        $order->user_id = $user->id;
        $order->business_id = $bill->business_id;
        $order->type = $bill->type;
        $order->device_id = 0;
        $order->bill_id = $billId;
        $order->house_id = $bill->house_id;
        $order->order_no = 'F' . date('ymdHis') . rand(1000, 9999);
        $order->pay_channel = $request->input('pay_channel', 'wx_lite');
        $order->pay_amt = $amount;
        $order->goods_title = $title;
        $order->goods_desc = $goodsDesc;
        $order->description = '';
        $order->fee = number_format($amount * 0.006, 2);

        $businessConf = BusinessConf::query()->where('business_id', $bill->business_id)->first();
        if ($businessConf && $businessConf->fee_payer == 2) {
            $order->pay_amt = $amount + $order->fee;
        }


//        $payment = $this->createPaymentOrder($order);
//
//        if ($payment->isError()) {
//            Log::error('支付出错啦', [$payment->result]);
//            return Result::error(500, '支付出错啦');
//        }
        $baofu = App::make(Baofu::class); // 通过容器解析依赖
        $result = $baofu->createOrder($order, $user);
        $order->save();
        $result['order_no'] = $order->order_no;
//        $result = $payment->result;
        return Result::success($result);
    }

    public function createPaymentOrder($order): \AdaPaySdk\Payment
    {
        $payment = AdaPayService::getPayment();

        # 支付设置
        $payment_params = [
            "app_id" => AdaPayService::getAppId(),
            "order_no" => $order->order_no,
            "pay_channel" => $order->pay_channel,
            "time_expire" => now()->addMinutes(3)->format('YmdHis'),
            "pay_amt" => str_replace(",", "", number_format($order->pay_amt, 2)),
            "goods_title" => $order->goods_title,
            "goods_desc" => $order->goods_desc,
            "description" => $order->description,
            'notify_url' => env('APP_URL') . '/api/payment/notify'
        ];
        # 微信小程序支付
        if ($order->pay_channel == 'wx_lite') {
            $payment_params["expend"] = [
                'open_id' => $order->user->openid,
                'wx_app_id' => env('MP_APP_ID')
            ];
        }
        if ($order->pay_channel == 'alipay_lite') {
            $payment_params['expend'] = [
                'buyer_id' => $order->user->alipay_id,
            ];
        }
        # 发起支付
        $payment->create($payment_params);
        return $payment;
    }

    public function orderStatus(Request $request)
    {
        Log::notice('orderStatus', [$request->all()]);
        $orderNo = $request->input('orderNo');

        $order = Order::query()->where('order_no', $orderNo)->first();
        if (!$order) {
            return Result::error(401, '订单不存在');
        }
        if ($order->status == 3) {
            return Result::success(['is_paid' => 1]);
        }
        return Result::success(['is_paid' => 0]);
    }

    public function orderFail(Request $request)
    {
        $orderId = $request->input('orderId');
        $order = Order::query()->find($orderId);
        if ($order) {
            $order->is_fail = 1;
            $order->save();
        }
        return Result::success([]);
    }
}
